#include <iostream>
#include <string>
#include <cstdlib>
#include <unistd.h>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <memory>
#include "Log.hpp"
#include <sys/types.h>
int main(int argc,char* argv[])//给服务器发送消息，需要传递 ip 和端口号port
{
    if(argc!=3)
    {
        logMessage(ERROR,"%s","参数传递错误：./xxx ip port");
        exit(1);
    }
    //创建套接字
    int sock = socket(AF_INET,SOCK_DGRAM,0);
    if(sock<0)//创建套接字失败
    {
        logMessage(ERROR,"%s","socket creation failure");
        exit(2);
    }
    std::string message; // 发送的信息
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(argv[1]);//填充ip
    server.sin_port = htons(atoi(argv[2]));//填充端口号
    char buffer[1024];
    // std::cout<<1<<std::endl;
    while (true)
    {
        std::cout << "请输入你的信息# ";
        std::getline(std::cin, message);
        if (message == "quit")
            break;
        // 当client首次发送消息给服务器的时候，OS会自动给client bind他的IP和PORT
        sendto(sock,message.c_str(),message.size(),0,(struct sockaddr*)&server,sizeof(server));//给服务器发送消息
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        //接受服务器的消息返回
        ssize_t s = recvfrom(sock,buffer,sizeof (buffer),0,(struct sockaddr*)&temp,&len);
        if(s>0)
        {
            buffer[s]=0;
            std::cout<<"server back# "<<buffer<<std::endl;
        }
    }
    return 0;
}